#include "precompiled/pchkrayserkraw.h"
#include "kraw/kraw3dmaterial.h"

#include "kernel/nkernelserver.h"

//-----------------------------------------------------------------------------

class KrawMaterialNode : public nStrNode
{
public:
    KrawMaterialNode( const char* name, Kraw3DMaterial* mat ) :
        nStrNode(name),
        pMaterial(mat)
    {
    }

    Kraw3DMaterial* pMaterial;
};

class KrawMaterialList : public nStrList
{
public:
    KrawMaterialList() : nStrList() {}
    ~KrawMaterialList()
    {
        KrawMaterialNode* node;
        while ( node = (KrawMaterialNode*) this->RemHead() )
        {
            n_delete( node->pMaterial );
            n_delete( node );
        }
    }
};

KrawMaterialList library;

//-----------------------------------------------------------------------------

Kraw3DMaterial* Kraw3DMaterial::Create( const char *name )
{
    //look for the material in the list
    KrawMaterialNode* node = (KrawMaterialNode*) library.Find( name );
    if ( node && node->pMaterial ) 
    {
        if ( !node->pMaterial->IsValid() ) node->pMaterial->Init();
        return node->pMaterial;
    }

    //TODO- create a new one through a material builder?

    return 0;
}

//-----------------------------------------------------------------------------

void Kraw3DMaterial::Cleanup()
{
    KrawMaterialNode* node = (KrawMaterialNode*) library.GetHead();
    while ( node )
    {
        n_delete( node->pMaterial );
        node->pMaterial = 0;
        node = (KrawMaterialNode*) node->GetSucc();
    }
}

//-----------------------------------------------------------------------------

Kraw3DMaterial::Kraw3DMaterial() :
    bIsValid(false)
{
}

//-----------------------------------------------------------------------------

void Kraw3DMaterial::Register( const char* name )
{
    KrawMaterialNode* node = n_new( KrawMaterialNode( name, this ) );
    library.AddTail( node );
}

//-----------------------------------------------------------------------------

bool Kraw3DMaterial::Init()
{
    bIsValid = true;
    return true;
}

//-----------------------------------------------------------------------------

void Kraw3DMaterial::SetWorldMatrix( const matrix44& mWorld )
{
    this->mWorld = mWorld;
}
